<template>
  <div class="category-wrapper">
    <div class="category-container" ref="categoryRef" @scroll="onCategoryScroll" v-if="typeRef === 'all'">
      <el-collapse v-model ="activeNames">
        <el-collapse-item v-for="(item, index) in illustrationCategoryData" :title="item.name" :name="index">
          <!-- <el-row class="col-tip mt-5">
            <el-col :span="5" class="col-name">
              <el-tag>{{ item.name }}</el-tag>
            </el-col>
            <el-col :span="7" class="col-name">
              <el-button text @click="showTotal(item.type)">{{ $t("message.all") }}<IconRight/></el-button>
            </el-col>
          </el-row> -->
          <el-row class="category-box" v-loading="item.category.length === 0">
            <el-col :span="8" class="box-image" v-for="(img, index) in item.category" :key="index">
              <img :src="img.previewURL" :alt="img.tags" @click="createImage(img)"/>
              <span class="box-image-name">{{img.tags}}-{{index+1}}</span>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="category-container" ref="totalRef" @scroll="onTotalScroll" v-else>
      <el-row class="col-tip mt-5">
        <el-col :span="7" class="col-name">
          <el-button text @click="hideTotal()"><IconLeft />{{ categoryData.name }}</el-button>
        </el-col>
      </el-row>
      <el-row class="total-box mt-5" v-loading="categoryData.total.length === 0">
        <div class="box-image" v-for="(img, index) in categoryData.total" :key="index" :style="{ justifyContent: index % 2 === 0 ? 'flex-start' : 'flex-end'}">
          <img :src="img.previewURL" :alt="img.tags" @click="createImage(img)"/>
        </div>
      </el-row>
    </div>
    <el-row class="image-bottom">{{ $t("message.endOfContent") }}</el-row>
  </div>
</template>

<script setup>
import { vue,axios} from '@core';
const { onMounted, ref, computed } = vue;
import restPath from "@views/fabric/api/image";

import { debounce, throttle } from "lodash-es";
import { useMainStore } from "@views/fabric/store";
import { storeToRefs } from "pinia";
import { util } from "fabric";
import { GifImage } from '@views/fabric/extension/object/GifImage'
import useHandleCreate from "@views/fabric/hooks/useHandleCreate";
import useCanvas from "@views/fabric/Canvas/useCanvas";
import { Image } from "fabric";
import useCenter from "@views/fabric/Canvas/useCenter";
const mainStore = useMainStore();
const { illustrationCategoryType, illustrationCategoryData } = storeToRefs(mainStore);
const { createImageElement } = useHandleCreate();

const activeNames = ref([]);

const categoryRef = ref();
const totalRef = ref();
const categoryTop = ref(0);
const typeRef = ref("all");
const categoryData = computed(() => {
  return illustrationCategoryData.value.filter(
    (ele) => ele.type === typeRef.value
  )[0];
});
const getImageCategoryData = throttle(
  async (t) => {
    let data = require(`@views/fabric/api/image/${t}.json`)
    illustrationCategoryData.value.filter((item) => item.type === t).map((ele) => (ele.category = data.data));
  },0,{ leading: true, trailing: false }
);

const getImagePageData = throttle(
  async (t, page= 1) => {
    axios
        .get(restPath.image.getIllustrationPages, {params: { t, page }})
        .then((res) => {
          if (res && res.data.code === 200) {
            illustrationCategoryData.value
              .filter((item) => item.type === t)
              .map((ele) => (ele.total = res.data.data));
          }
        }).catch((e) => {
            console.log("查询出错：" + e);
        });
  },
  100,
  { leading: true, trailing: false }
);

const getContainScroll = () => {
  let startIndex = 0,
    endIndex = 2;
  if (!categoryRef.value)
    return {
      startIndex,
      endIndex,
    };
  const scrollTop = categoryRef.value.scrollTop;
  const containerHeight = categoryRef.value.clientHeight;
  const itemHeight = 132;
  startIndex = Math.floor(scrollTop / itemHeight);
  endIndex = Math.ceil((scrollTop + containerHeight) / itemHeight);
  return {
    startIndex,
    endIndex,
  };
};

const onCategoryScroll = async () => {
  const { startIndex, endIndex } = getContainScroll();
  for (let i = startIndex; i < endIndex; i++) {
    const item = illustrationCategoryData.value[i];
    if (!item) return;
    if (!illustrationCategoryType.value.includes(item.type)) {
      activeNames.value.push(i);
      illustrationCategoryType.value.push(item.type);
      await getImageCategoryData(item.type);
    }
    // if (item.category.length === 0) {
    //   await getImageCategoryData(item.type)
    // }
  }
};

const onTotalScroll = async () => {
  const { startIndex, endIndex } = getContainScroll();
  for (let i = startIndex; i < endIndex; i++) {
    const item = illustrationCategoryData.value[i];
    if (!item) return;
    if (!illustrationCategoryType.value.includes(item.type)) {
      illustrationCategoryType.value.push(item.type);
      await getImageCategoryData(item.type);
    }
    // if (item.category.length === 0) {
    //   await getImageCategoryData(item.type)
    // }
  }
};

const showTotal = async (type) => {
  if (!categoryRef.value) return;
  categoryTop.value = categoryRef.value.scrollTop;
  typeRef.value = type;
  await getImagePageData(type, 1);
};

const hideTotal = () => {
  typeRef.value = "all";
  if (!categoryRef.value) return;
  categoryRef.value.scrollTo({ top: categoryTop.value, behavior: "smooth" });
};

const hideLoading = async (item, loading) => {
  const [ canvas ] = useCanvas()
  await util.loadImage(item.largeImageURL)
  loading.set({visible: false})
  canvas.renderAll()
}

const createImage = async (item) => {
  
  const [ canvas ] = useCanvas()
  const { centerPoint } = useCenter()
  let loading = canvas.loading
 
  if (!loading) {
    let image_load = require(`/static/images/loading.gif`).default;
    loading = await GifImage.fromURL(image_load);
    loading.set({left: centerPoint.x - loading.width / 2, top: centerPoint.y - loading.height / 2})
    
    canvas.add(loading);
    canvas.renderAll()
    canvas.loading = loading
    
  }
  else {
    loading.set({visible: true})
    canvas.bringObjectToFront(loading)
    canvas.renderAll()
  }
  await hideLoading(item, loading)
  createImageElement(item.largeImageURL);
};

onMounted(() => {
  if (!categoryRef.value) return;
  onCategoryScroll();
});
</script>

<style lang="scss" scoped>
.col-tip {
  justify-content: space-between;
  align-items: center;
}
.col-name {
  text-align: center;
}
.mt-5 {
  margin-top: 5px;
}
.category-wrapper{
  height:100%;
  width:100%;
  position:relative;
  overflow:hidden;
}
.category-box {
  .box-image {
    display: flex;
    flex-direction: column;
    justify-content:flex-start;
    align-items: center;
    padding: 5px;
    box-sizing:border-box;
    img {
      width: 30px;
      height:30px;
      cursor: pointer;
    }
    .box-image-name{
      padding:5px 0;
      width:100%;
      text-align:center;
      line-height:1.4;
      display: -webkit-box;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }
}

.category-container {
  overflow-y: scroll;
  height: 100%;
  align-items: center;
  :deep(.el-collapse-item__content){
    padding-bottom:10px;
  }
}
.total-box {
  .box-image {
    padding: 2px;
    width: 48%;
    height: 120px;
    overflow: hidden;
    display: flex;
    img {
      max-width: 100%;
    }
  }
}
.image-bottom {
  justify-content: center;
  padding-top: 20px;
  margin-bottom: 130px;
}
</style>